var express = require('express');
var router = express.Router();
var jwt = require("jsonwebtoken");
const secret = "goyangforum";  //秘钥
const { mysqlCreate } = require('./utils');
var mysql = require('mysql');

//连接数据库
let conn = mysqlCreate();

router.get('/', (req, res) => {
  conn = mysql.createConnection(conn.config); 
  // console.log(req.headers.authorization)
  //定义token验证中间件函数（应用于除登录外的每个请求）
  //获取传递的参数
  const type = req.query;
  if (type.headers) {
    //获取客户端发送来的token
    const token = JSON.parse(type.headers).Authorization;
    jwt.verify(token, secret, (err, decoded)=>{
      if(err){
        console.log(err)
      }else{
        let sql = `SELECT * FROM user where name = ${decoded.user}`; //创建数据库查询的语法
        conn.connect();
        conn.query(sql, function (err, result){
          if(err){
            console.log('[SELECT ERROR] - ',err.message);
            res.json({ code: -1 })
          }else{
            if(result.length == 0){
              res.json({code: -1, message:"用户不存在"})
            }else if(result[0].name !== decoded.user){
              res.json({code: -1, message:"用户信息不正确"})
            }else{
              // delArt(type);
              let sqls = `DELETE FROM article WHERE id = ${type.id}`; //创建数据库查询的语法
              conn.query(sqls, function(err,result){
                if(err){
                  res.json({code: -3, message: "删除失败"})
                  console.log(err)
                }else{
                  res.json({code:40000, message:"删除成功", data:result})
                }
              })
            }
          }
        });
      }
    })
  }else{
    res.json({ code: -2, message: "没有正确的头信息"})
  }

  // function delArt(type){
  //   let sqls = `DELETE FROM article WHERE id = ${type.id}`; //创建数据库查询的语法
  //   conn.query(sqls, function(err,result){
  //     if(err){
  //       res.json({code: -3, message: "删除失败"})
  //       console.log(err)
  //     }else{
  //       res.json({code:40000, message:"删除成功", data:result})
  //     }
  //   })
  // }
})



module.exports = router;
